<script setup>
import {defineComponent, onMounted, ref} from "vue";
import TaskLane from "@/views/task/components/TaskLane.vue";
const taskStore = useTaskStore();
import {VueDraggable} from "vue-draggable-plus";
import {useRoute} from "vue-router";
import {queryLine, updateSort} from "@/api/line.js";
import AddLine from "@/views/task/components/AddLine.vue";
import {useTaskStore} from "@/stores/index.js";
import {ElMessageBox} from "element-plus";
import {deleteTask} from "@/api/task.js";
import {message} from "ant-design-vue";


defineComponent({
  name: "TaskContent",
});

const route = useRoute();
const taskId = ref("")
onMounted(() => {
  taskId.value = route.params.taskId
  syncList()
  getLineList()
})
let list = ref([]);
const getLineList = async () => {
  const param = {
    id:taskId.value
  }
  let res = await queryLine(param);
  if (res.code === 200) {
    list.value = res.data

  }
}


// 拖拽事件发生
const handleLineUpdate = (e) => {
  const {data, oldIndex, newIndex} = e
  // console.log("===== Update ======",data, oldIndex, newIndex)
  const oldIndexSort = list.value[oldIndex].sort;
  list.value[oldIndex].sort = list.value[newIndex].sort;
  list.value[newIndex].sort = oldIndexSort;
  // 更新缓存
  taskStore.updateLineInfo(list.value);
  if (saveTime.value == null) {
    autoSaveList()
  }
}
const handleLineAdd = (e) => {

}

// 轮询保存
let saveTime = ref(null)
function autoSaveList() {
  saveTime.value = setInterval(async () => {
    const res = await updateSort({list: list.value})
    if (res.code === 200) {
      taskStore.removeLineInfo()
    }
  },60* 1000)
}
// 如果数据没有同步
const syncList = () => {
  // 获取同步状态
  const list = taskStore.getLineList();

  const status = taskStore.getLineStatus()

  if (!status && list.length > 0) {
    ElMessageBox.confirm("是否需要同步上一次面板排序？",
        "Warning",
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
      const res = await updateSort({list})
      if (res.code === 200) {
        message.success("同步成功")
        await getLineList()
      }
    }).catch()
        .finally(() => {
         taskStore.removeLineInfo()
        })
  }
}
</script>

<template>
  <div class="page-box">
    <VueDraggable class="page-container"
                  v-model="list"
                  animation="500"
                  group="line"
                  :on-update="handleLineUpdate"
                  :on-add="handleLineAdd"
    >
      <template v-for="item in list">
        <TaskLane :line="item" @delSuccess="getLineList" />
      </template>
      <add-line :taskId="taskId" @addLineSuccess="getLineList"></add-line>
    </VueDraggable>
  </div>
</template>

<style scoped lang="less">
.page-box {
  height: 100%;
  width: 100%;
  background: #fff;
  overflow: auto;
}

.page-container {
  display: flex;
  align-items: flex-start;

}
</style>
